from flask import render_template,request
from app import db
from . import auth_notice
from .model import Notice
from .service import NoticeService
from apps.utils.TypeUtils import TypeUtils
import json
import uuid
import time

@auth_notice.route('/save',methods = ['GET','POST'])
def save():
    data = {}
    if request.method == "POST":
        for key in request.form:
            data[key] = request.form.get(key)
    else:
        for key in request.args:
            data[key] = request.args.get(key)
    notice = Notice()
    if data['notice_pk'] is None:
        notice.notice_pk = str(uuid.uuid1())
    else:
        notice.notice_pk = data['notice_pk']
    notice.fk_user_pk = data['fk_user_pk']
    notice.notice_content = data['notice_content']
    notice.notice_person = data['notice_person']
    # notice.notice_remark = data['notice_remark']
    notice.notice_title = data['notice_title']
    notice.notice_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    if data['notice_pk'] is None:
        NoticeService.save(notice)
    else:
        NoticeService.update(notice)
    data = {
        'msg':'保存成功',
        'code':'0',
    }
    return json.dumps(data,ensure_ascii=False)
#获取通知信息的分页列表
@auth_notice.route('/list',methods=['GET','POST'])
def list():
    notices = NoticeService.list() 
    dicts = [ TypeUtils.list_to_dict(notice) for notice in notices ]
    return json.dumps(dicts,ensure_ascii=False)

#获取通知信息的分页列表
@auth_notice.route('/pages',methods=['GET','POST'])
def pages():
    if request.method == "POST":
        page = request.form.get("page")  #获取页码
    else:
        page = request.args.get("page")
    pages = NoticeService.pages(page) #flask_sqlalchemy提供分页方法.paginate

    data = {
        'msg':'success',
        'code':'0',
        'data':[TypeUtils.list_to_dict(notice) for notice in pages.items],
        'count':pages.total
    }

    print(pages.items)
    return json.dumps(data,ensure_ascii=False)  #关闭已ascii编码输出